<?php
/**
 * +----------------------------------------------------------------------+
 * php23种设计模式实现-解释器模式
 * Author：微信公众号：yuantanphp
 * 获取更多资源，技术答疑，项目合作请关注微信公众号：yuantanphp
 * +----------------------------------------------------------------------+
 */
namespace Interpreter;
/**
 * 抽象表达类
 * Class Expression
 */
abstract class Expression
{
    //待解释信息
    abstract public function interpret($info);
}
/**
 * 终结符表达式类
 * Class TerminalExpression
 */
class TerminalExpression extends Expression
{
    private $restaurants = [];

    public function __construct(array $restaurants)
    {
        $this->restaurants = $restaurants;
    }

    public function interpret($info)
    {
        // TODO: Implement interpret() method.
        if (in_array($info, $this->restaurants)) {
            return true;
        } else {
            return false;
        }
    }
}

/**
 * 非终结符表达式类
 * Class AndExpression
 */
class AndExpression extends Expression
{
    private $restaurantsExpression;
    private $role;
    public function __construct(Expression $restaurantsExpression)
    {
        $this->restaurantsExpression = $restaurantsExpression;
    }

    public function interpret($info)
    {
        $info = explode("去",$info);
        $role = $info[0];
        $this->role = $role;
        $restaurant = $role."餐厅";
        return $this->restaurantsExpression->interpret($restaurant);
    }
    public function getRole(){
        return $this->role;
    }
}

/**
 * Class Context
 * 上下文
 */
class Context
{
    //餐厅列表
    private $restaurants = ["高层领导餐厅", "贵宾餐厅", "中基层员工餐厅"];
    private $restaurantsPerson;

    public function __construct()
    {
        $restaurantsExpression = new TerminalExpression($this->restaurants);
        $this->restaurantsPerson = new AndExpression($restaurantsExpression);
    }

    public function havingDinner($info)
    {
        $isTrue = $this->restaurantsPerson->interpret($info);
        $role = $this->restaurantsPerson->getRole();
        if ($isTrue) {
            echo "当前角色 " . $role . "，请前往 ".$role."餐厅<br />";
        } else {
            echo "当前角色 " . $role . " - 暂未找到匹配到该角色的餐厅<br />";
        }
    }
    
}
$content = new Context();
$content->havingDinner("高层领导去食堂吃饭");
$content->havingDinner("贵宾去食堂吃饭");
$content->havingDinner("中基层员工去食堂吃饭");
$content->havingDinner("游客去食堂吃饭");